package com.ruoyi.voucher.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Summary;
import com.ruoyi.voucher.domain.Examine;
import com.ruoyi.voucher.domain.Voucher;

import com.ruoyi.voucher.domain.VoucherWord;
import com.ruoyi.voucher.domain.dto.VoucherImportDTO;
import com.ruoyi.voucher.service.IVoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 凭证主表Controller
 *
 * @author ruoyi
 * @date 2025-02-25
 */

@RestController
@RequestMapping("/finance_voucher/voucher")
public class VoucherController extends BaseController
{
                 @Autowired
                 IVoucherService voucherService;
    /**
     * 查询凭证主表列表
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:list')")
    @GetMapping("/list")
    public TableDataInfo list(Voucher voucher)
    {
        startPage();
        List<Voucher> list = voucherService.selectVoucherList(voucher);
        return getDataTable(list);
    }

    /**
     * 导出凭证主表列表
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:export')")
    @Log(title = "凭证主表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Voucher voucher)
    {
        List<Voucher> list = voucherService.selectVoucherList(voucher);
        ExcelUtil<Voucher> util = new ExcelUtil<Voucher>(Voucher.class);
        util.exportExcel(response, list, "凭证主表数据");
    }

    /**
     * 获取凭证主表详细信息
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:query')")
    @GetMapping(value = "/{voucherId}")
    public AjaxResult getInfo(@PathVariable("voucherId") Long voucherId)
    {
        return success(voucherService.selectVoucherByVoucherId(voucherId));
    }

    /**
     * 新增凭证主表
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:add')")
    @Log(title = "凭证主表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Voucher voucher)
    {
        return toAjax(voucherService.insertVoucher(voucher));
    }

    /**
     * 修改凭证主表
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:edit')")
    @Log(title = "凭证主表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Voucher voucher)
    {
        return toAjax(voucherService.updateVoucher(voucher));
    }

    /**
     * 删除凭证主表
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:remove')")
    @Log(title = "凭证主表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{voucherIds}")
    public AjaxResult remove(@PathVariable Long[] voucherIds)
    {
        return toAjax(voucherService.deleteVoucherByVoucherIds(voucherIds));
    }

    /**
     * 审核凭证
     */
     @PutMapping("/auditVoucher/{voucherId}")
     @Transactional
    public AjaxResult auditVoucher(@PathVariable("voucherId") Long voucherId)
    {
        //先获取道当前登录人的姓名
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //登陆人就是当前要审核的凭证的审核人
        Voucher voucher = voucherService.selectVoucherByVoucherId(voucherId);
        if (voucher == null){
          return AjaxResult.error("凭证不存在");
        }
        //判断作废状态不能审核
        if(voucher.getIsVoid()==2){
            return AjaxResult.error("凭证已作废，不能审核");
        }
        if(voucher.getAuditStatus().equals("未审核")){
            voucher.setAuditorId(loginUser.getUserId());
            voucher.setAuditStatus(loginUser.getUsername());
            voucherService.updateVoucher(voucher);

        }else{
            return AjaxResult.error("凭证已审核，不能重复审核");
        }

        //给中间表添加了一条审核记录
        Examine examine = new Examine();
        examine.setVoucherId(voucher.getVoucherId());
        examine.setUserId(loginUser.getUserId());
        examine.setOperate("审核");
        voucherService.insertExamine(examine);


        return AjaxResult.success("审核成功");

    }


    /**
     * 反审核凭证
     */
    @PutMapping("/unAuditVoucher/{voucherId}")
    @Transactional
    public AjaxResult unAuditVoucher(@PathVariable("voucherId") Long voucherId) {
        Voucher voucher = voucherService.selectVoucherByVoucherId(voucherId);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (voucher == null) {
            return AjaxResult.error("凭证不存在");
        }
       // 判断作废状态不能反审核
        if (voucher.getIsVoid() == 2) {
            return AjaxResult.error("凭证已作废，不能反审核");
        }
        if (voucher.getAuditStatus().equals("未审核")) {
            return AjaxResult.error("凭证未审核，不能反审核");
        }
        //判读审核状态是否有值
        if (voucher.getAuditStatus() != null) {
            voucher.setAuditStatus("未审核");
            voucherService.updateVoucher(voucher);
        }
        Examine examine = new Examine();
        examine.setVoucherId(voucher.getVoucherId());
        examine.setUserId(loginUser.getUserId());
        examine.setOperate("反审核");
        voucherService.insertExamine(examine);

        return AjaxResult.success("请重新审核");


    }



    /**
     * 作废凭证
     */
    @PutMapping("/cancellation/{voucherId}")
    @Transactional
    public AjaxResult cancellation(@PathVariable("voucherId") Long voucherId) {

        //获取当前想要报废人的信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //通过这个凭证id获取到凭证信息
        Voucher voucher = voucherService.selectVoucherByVoucherId(voucherId);
        //判断凭证是否存在
        if (voucher == null) {
            return AjaxResult.error("凭证不存在");
        }
        //通过凭证id获取到凭证信息 判断是否已经作废
        if (voucher.getIsVoid() == 2) {
            return AjaxResult.error("凭证已作废，不能重复作废");
        }
        //判断凭证是否已经审核
       if (!voucher.getAuditStatus().equals("未审核")){
           return AjaxResult.error("凭证已审核，不能作废");
       }
        //修改他的作废状态
        if (voucher.getIsVoid() == 1){
            voucher.setIsVoid(2);
            voucherService.updateVoucher(voucher);
        }

        Examine examine = new Examine();
        examine.setVoucherId(voucher.getVoucherId());
        examine.setUserId(loginUser.getUserId());
        examine.setOperate("作废");
        voucherService.insertExamine(examine);
        return AjaxResult.success("作废成功");


    }


    /*
    冲红
     */
    @PutMapping("/redraw/{voucherId}")
    @Transactional
    public AjaxResult redraw(@PathVariable("voucherId") Long voucherId) {
        //获取当前操作人的信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取当前想要红冲的表信息
        Voucher voucher = voucherService.selectVoucherByVoucherId(voucherId);
        //判断凭证是否存在
        if (voucher == null) {
            return AjaxResult.error("凭证不存在");
        }
        //判断凭证作废的不能进行红冲
        if (voucher.getIsVoid() == 2) {
            return AjaxResult.error("凭证已作废，不能进行红冲");
        }
        //只有凭证审核完成的才可以进行红冲
        if (voucher.getAuditStatus().equals("未审核")) {
            return AjaxResult.error("凭证未审核，可以直接进行作废，不可以");
        }
        //给这个凭证添加一条冲红记录 这个凭证名字上拼接上冲红
        voucher.setVoucherNo(voucher.getVoucherNo() + "冲红");
        voucher.setAuditorId(loginUser.getUserId());
        voucher.setAuditStatus(loginUser.getUsername());
        voucher.setIsVoid(1);
       //添加一条红冲数据
        voucherService.insertVoucher(voucher);


       //给中间表添加一条数据 添加一条红冲记录
        Examine examine = new Examine();
        examine.setVoucherId(voucher.getVoucherId());
        examine.setUserId(loginUser.getUserId());
        examine.setOperate("冲红");
        voucherService.insertExamine(examine);


        return AjaxResult.success("冲红成功");
    }




    /**
     * 导入凭证数据
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:import')")
    @Log(title = "凭证导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<VoucherImportDTO> util = new ExcelUtil<>(VoucherImportDTO.class);
        List<VoucherImportDTO> voucherList = util.importExcel(file.getInputStream());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String message = voucherService.importVoucher(voucherList, loginUser.getUsername());
        return AjaxResult.success(message);
    }

    /**
     * 下载导入模板
     */
    @PreAuthorize("@ss.hasPermi('finance_voucher:voucher:import')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<VoucherImportDTO> util = new ExcelUtil<>(VoucherImportDTO.class);
        util.importTemplateExcel(response, "凭证数据");
    }






@GetMapping("/summary/lis")
    public TableDataInfo getVoucher() {
       List<VoucherWord>  summaryList =  voucherService.getList();
       return  getDataTable(summaryList);
    }













}
